package com.niji.littly_donkey_android.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.*;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.niji.littly_donkey_android.R;
import com.niji.littly_donkey_android.adapter.TicketAdapter;
import com.niji.littly_donkey_android.bean.Ticket;
import com.niji.littly_donkey_android.http.ConnectViaSession;
import com.niji.littly_donkey_android.util.*;
import com.niji.littly_donkey_android.view.TicketListView;
import org.codehaus.jackson.map.util.BeanUtil;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

public class ScreenDetailsActivity extends AppCompatActivity {

    private static final String TAG = "ScreenDetailsActivity";

    private Button screen_details_return;

    private Button screen_details_comment;

    private Button screen_details_reserve;

    private TextView screen_details_tickets;

    private static Integer attractions_id = -1;

    private static Integer descriptionHight = 0;

    private TextView screen_ticket_info;

    private RelativeLayout screen_ticket_loading;

    private static String UUnotes;


    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen_details);
        initialization();
        screenDetailsReturn();
        screenDetailsComment();
//        screenDetailsReserve();
        screenDetailsTickets();
        getScreenDetails();
        changeDescription();
        changePlayAndTickets();
        StatusBarColor.setStatusBarColor(ScreenDetailsActivity.this,Color.parseColor("#000000"));
    }

    /**
     * 获取景点门票信息
     */
    private void getTicketList(){
        TicketListView tickets_list = findViewById(R.id.tickets_list);
        screen_ticket_info = findViewById(R.id.screen_ticket_info);
        screen_ticket_loading = findViewById(R.id.screen_ticket_loading);
        screen_ticket_info.setVisibility(View.GONE);
//        String url = UrlUtil.URL + "/attractions/ticket/list?attractions_id=" + attractions_id;
        String url = UrlUtil.URL + "/attractions/ticket/list?attractions_id=" + attractions_id;
        ArrayList<Ticket> tickets = new ArrayList<>();
        RequestQueue requestQueue = Volley.newRequestQueue(ScreenDetailsActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    Map<String, Object> map = JsonUtil.jsonToMap(s);
                    Integer code = (Integer) map.get("code");
                    if (code == 0) {
                        List<Map<String, Object>> mapList = (List<Map<String, Object>>) map.get("data");
                        Log.i(TAG, mapList.toString());
                        for (int i = 0; i < mapList.size(); i++) {
                            Ticket ticket = EntityUtils.mapToEntity(mapList.get(i), Ticket.class);
                            ticket.setAttractions_id(attractions_id);
                            tickets.add(ticket);
                        }
                        screen_ticket_loading.setVisibility(View.INVISIBLE);
                        screen_ticket_info.setVisibility(View.INVISIBLE);
                        tickets_list.setAdapter(new TicketAdapter(ScreenDetailsActivity.this,tickets));
                    } else if (code == -1) {
                        Toast.makeText(ScreenDetailsActivity.this, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(ScreenDetailsActivity.this, GetPhoneCodeActivity.class);
                        intent.putExtra("loginCode", "-1");
                        startActivity(intent);
                        finish();
                    } else {
                        Object message = map.get("message");
                        Toast.makeText(ScreenDetailsActivity.this, message.toString(), Toast.LENGTH_SHORT).show();
                        overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                        finish();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(ScreenDetailsActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show();
                screen_ticket_loading.setVisibility(View.INVISIBLE);
                screen_ticket_info.setVisibility(View.VISIBLE);
            }
        }) {
            @Override
            public Request<?> setRetryPolicy(RetryPolicy retryPolicy) {
                return super.setRetryPolicy(new DefaultRetryPolicy(5000,3,1.0F));
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String sesseionid = new ConnectViaSession(ScreenDetailsActivity.this).GetSession();
                if (!sesseionid.equals("")) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("cookie", sesseionid);
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };
        requestQueue.add(stringRequest);

    }


    /**
     * 切换游玩攻略和购票须知
     */
    private void changePlayAndTickets() {
        ImageView  screen_details_play_img = findViewById(R.id.screen_details_play_img);
        ImageView  screen_details_tickets_img = findViewById(R.id.screen_details_tickets_img);
        TextView  screen_details_play = findViewById(R.id.screen_details_play);
        TextView  screen_details_tickets = findViewById(R.id.screen_details_tickets);
        LinearLayout  screen_show_raiders = findViewById(R.id.screen_show_raiders);
        LinearLayout  screen_show_ticket_notice = findViewById(R.id.screen_show_ticket_notice);
        screen_details_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                screen_details_play.setTextColor(Color.parseColor("#333333"));
                screen_details_tickets.setTextColor(Color.parseColor("#999999"));
                screen_details_play_img.setVisibility(View.VISIBLE);
                screen_details_tickets_img.setVisibility(View.INVISIBLE);
                screen_show_raiders.setVisibility(View.VISIBLE);
                screen_show_ticket_notice.setVisibility(View.INVISIBLE);
            }
        });
        screen_details_tickets.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                screen_details_play.setTextColor(Color.parseColor("#999999"));
                screen_details_tickets.setTextColor(Color.parseColor("#333333"));
                screen_details_play_img.setVisibility(View.INVISIBLE);
                screen_details_tickets_img.setVisibility(View.VISIBLE);
                screen_show_raiders.setVisibility(View.INVISIBLE);
                screen_show_ticket_notice.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 收取全文/显示全文
     */
    private void changeDescription() {
        TextView screen_change_description = findViewById(R.id.screen_change_description);
        Button screen_show_description = findViewById(R.id.screen_show_description);
        Button screen_not_show_description = findViewById(R.id.screen_not_show_description);
        LinearLayout screen_details_description_parent = findViewById(R.id.screen_details_description_parent);

        screen_change_description.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setDescriptionHight();
            }
        });
        screen_show_description.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String showDecription = screen_change_description.getText().toString().trim();
                if(showDecription.equals("收起全文")){
                    screen_change_description.setText("展开全文");
                    if(descriptionHight < screen_details_description_parent.getHeight()){
                        descriptionHight = screen_details_description_parent.getHeight();
                    }
                    ViewGroup.LayoutParams para;
                    para = screen_details_description_parent.getLayoutParams();
                    para.height = 500;
                    screen_details_description_parent.setLayoutParams(para);

                }
            }
        });
        screen_not_show_description.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String showDecription = screen_change_description.getText().toString().trim();
                if(showDecription.equals("展开全文")){
                    screen_change_description.setText("收起全文");
                    ViewGroup.LayoutParams para;
                    para = screen_details_description_parent.getLayoutParams();
                    para.height = descriptionHight;
                    screen_details_description_parent.setLayoutParams(para);
                }
            }
        });
    }

    /**
     * 设置景点描述高度
     */
    private void setDescriptionHight(){
        TextView screen_change_description = findViewById(R.id.screen_change_description);
        LinearLayout screen_details_description_parent = findViewById(R.id.screen_details_description_parent);
        String showDecription = screen_change_description.getText().toString().trim();
        if(showDecription.equals("收起全文")){
            screen_change_description.setText("展开全文");
            if(descriptionHight < screen_details_description_parent.getHeight()){
                descriptionHight = screen_details_description_parent.getHeight();
            }
            ViewGroup.LayoutParams para;
            para = screen_details_description_parent.getLayoutParams();
            para.height = 500;
            screen_details_description_parent.setLayoutParams(para);

        }else  if(showDecription.equals("展开全文")){
            screen_change_description.setText("收起全文");
            ViewGroup.LayoutParams para;
            para = screen_details_description_parent.getLayoutParams();
            para.height = descriptionHight;
            screen_details_description_parent.setLayoutParams(para);
        }
    }


    /**
     * 获取景点详情信息
     */
    private void getScreenDetails() {
        TextView screen_details_id = findViewById(R.id.screen_details_id);
        TextView screen_details_name = findViewById(R.id.screen_details_name);
        ImageView screen_details_top = findViewById(R.id.screen_details_top);
        WebView screen_details_description =  findViewById(R.id.screen_details_description);
        WebView screen_details_raiders =  findViewById(R.id.screen_details_raiders);
        WebView screen_details_ticket_notice =  findViewById(R.id.screen_details_ticket_notice);
        TextView screen_details_score = findViewById(R.id.screen_details_score);
        TextView screen_details_comments = findViewById(R.id.screen_details_comments);
        TextView screen_details_address = findViewById(R.id.screen_details_address);
        TextView screen_details_open_end_time = findViewById(R.id.screen_details_open_end_time);
        String url = UrlUtil.URL + "/attractions/info?id=" + attractions_id;
        RequestQueue requestQueue = Volley.newRequestQueue(ScreenDetailsActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    Map<String, Object> map = JsonUtil.jsonToMap(s);
                    Integer code = (Integer) map.get("code");
                    if (code == 0) {
                        Map<String, Object> dataMap = (Map) map.get("data");
                        Log.i(TAG, dataMap.toString());
                        Integer id = (Integer) dataMap.get("id");
                        String name = (String) dataMap.get("name");
                        String top_url = (String) dataMap.get("top_url");
                        String description = (String) dataMap.get("description");
                        String raiders = (String) dataMap.get("raiders");
                        String ticket_notice = (String) dataMap.get("ticket_notice");
                        String score = (String) dataMap.get("score");
                        Integer comments = (Integer) dataMap.get("comments");
                        String address = (String) dataMap.get("address");
                        String latitude_longitude = (String) dataMap.get("latitude_longitude");
                        String open_start = (String) dataMap.get("open_start");
                        String open_end = (String) dataMap.get("open_end");
                        String created_at = (String) dataMap.get("created_at");
                        screen_details_description.loadDataWithBaseURL("",HtmlUtil.getHtmlData(description),"text/html","utf-8",null);
                        screen_details_raiders.loadDataWithBaseURL("",HtmlUtil.getHtmlData(raiders),"text/html","utf-8",null);
                        screen_details_ticket_notice.loadDataWithBaseURL("",HtmlUtil.getHtmlData(ticket_notice),"text/html","utf-8",null);
                        if(top_url != null){
                            if (!top_url.equals("")){
                                NetworkGlideImageLoader.getInstance().displayImage((Activity) ScreenDetailsActivity.this, UrlUtil.URL + top_url, screen_details_top, 0, 0);
                            }
                        }
                        screen_details_id.setText("" + id);
                        screen_details_name.setText(name);
//                        screen_details_description.setText(description);
                        screen_details_score.setText(score);
                        screen_details_comments.setText(comments + " 评价");
                        screen_details_address.setText(address);
                        screen_details_open_end_time.setText("开放时间 " + open_start + "-" + open_end);

                    } else if (code == -1) {
                        Toast.makeText(ScreenDetailsActivity.this, "登录失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(ScreenDetailsActivity.this, GetPhoneCodeActivity.class);
                        intent.putExtra("loginCode", "-1");
                        startActivity(intent);
                        finish();
                    } else {
                        Object message = map.get("message");
                        Toast.makeText(ScreenDetailsActivity.this, message.toString(), Toast.LENGTH_SHORT).show();
                        overridePendingTransition(R.anim.xpage_slide_in_left, R.anim.xpage_slide_out_right);
                        finish();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String sesseionid = new ConnectViaSession(ScreenDetailsActivity.this).GetSession();
                if (!sesseionid.equals("")) {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("cookie", sesseionid);
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };
        requestQueue.add(stringRequest);
    }


    private void initialization() {
        Intent intent = getIntent();
        String attractions_id = intent.getStringExtra("attractions_id");
        this.attractions_id = Integer.parseInt(attractions_id);
        getTicketList();

    }

    @Override
    protected void onStart() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            //不加这个clearFlags好像就没效果
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            //设置导航栏透明(就是虚拟键那一栏)
             
            //设置状态栏(或者叫通知栏)透明
             
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        super.onStart();
    }

    /**
     * 界面设置状态栏字体颜色
     */
    public void changeStatusBarTextImgColor(boolean isBlack) {
        if (isBlack) {
            //设置状态栏黑色字体
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            //恢复状态栏白色字体
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        }
    }

    private void screenDetailsTickets() {
        screen_details_tickets = findViewById(R.id.screen_details_tickets);
        screen_details_tickets.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ScreenDetailsActivity.this, ScreenTicketsActivity.class));
                   
            }
        });
    }

    /**
     * 订单填写
     */
    private void screenDetailsReserve() {
        screen_details_reserve = findViewById(R.id.screen_details_reserve);
        screen_details_reserve.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ScreenDetailsActivity.this, OrderFillActivity.class));
                   
            }
        });
    }


    /**
     * 景点评论
     */
    private void screenDetailsComment() {
        TextView screen_details_score = findViewById(R.id.screen_details_score);
        TextView screen_details_comments = findViewById(R.id.screen_details_comments);
        screen_details_comment = findViewById(R.id.screen_details_comment);
        screen_details_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ScreenDetailsActivity.this, CommentActivity.class);
                intent.putExtra("attractions_id",attractions_id);
                startActivity(intent);
                   
            }
        });

        screen_details_comments.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ScreenDetailsActivity.this, CommentActivity.class);
                intent.putExtra("attractions_id",attractions_id);
                startActivity(intent);

            }
        });

        screen_details_score.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ScreenDetailsActivity.this, CommentActivity.class);
                intent.putExtra("attractions_id",attractions_id);
                startActivity(intent);

            }
        });


    }


    /**
     * 登录界面返回
     */
    private void screenDetailsReturn() {
        screen_details_return = findViewById(R.id.screen_details_return);
        screen_details_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                overridePendingTransition(R.anim.xpage_slide_in_left,R.anim.xpage_slide_out_right);
                finish();

            }
        });

    }
}
